//
//  CZOAuthViewController.m
//  小和微博
//
//  Created by 董晓合 on 15/2/23.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "CZOAuthViewController.h"
#import "CZAccount.h"
#import "CZNewfeatureViewController.h"
#import "CZWelcomeViewController.h"

#define CZAuthorizeUrl @"https://api.weibo.com/oauth2/authorize"
#define CZClientId @"1283951148"
#define CZClientSecret @"44217361ab0c1e96a1d09cf95c659b7e"
#define CZRedirectUri  @"http://ios.itcast.cn"
#define CZAccessTokenUrl @"https://api.weibo.com/oauth2/access_token"

@interface CZOAuthViewController ()<UIWebViewDelegate>

@end

@implementation CZOAuthViewController

- (void)loadView {

    self.view = [[UIWebView alloc] init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化导航条
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    
//    加载登陆界面
    [self loadOAuthPage];
}

- (void)loadOAuthPage {

//  1.拼接请求路径
    NSString *urlString = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",CZAuthorizeUrl,CZClientId,CZRedirectUri];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
//    加载网页
    UIWebView *webView = (UIWebView *)self.view;
    webView.delegate = self;
    [webView loadRequest:request];
}

- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIWebViewDelegate

//只要webView发送请求就会调用,YES代表继续加载 NO代表不允许加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
//    1.判断要请求的url中是否包含code=
    NSString *urlString = request.URL.absoluteString;
    NSRange range = [urlString rangeOfString:@"code="];
    if (range.location !=NSNotFound) {
        
//    2.截取获取到已经授权的RequestToken,缓存AccessToken
        NSUInteger startIndex = range.location + range.length;
        NSString *code = [urlString substringFromIndex:startIndex];
        
        [self accessTokenWith:code];
        return NO;
    }

    return YES;
}
/**
 *  根据已经授权的RequestToken换取AccessToken
 */
- (void)accessTokenWith:code {
    
//    1.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"client_id"] = CZClientId;
    parameters[@"client_secret"]  = CZClientSecret;
    parameters[@"grant_type"]  = @"authorization_code";
    parameters[@"code"]  = code;
    parameters[@"redirect_uri"]  = CZRedirectUri;
    
//    2.创建网络请求管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    让AFN支持text/plain类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
//    3.利用管理对象发送请求
    [manager POST:CZAccessTokenUrl parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        DDLogDebug(@"换取AccessToken成功 = %@", responseObject);
        /*
         "access_token" = "2.00vraupCU21t5B9c71d7d120GmPNjC";
         "expires_in" = 157679999;
         "remind_in" = 157679999;
         uid = 2599346895;
         */
//        1.将服务器返回的字典转换成模型
        CZAccount *account = [CZAccount objectWithKeyValues:responseObject];
        
//        2.将模型保存到沙盒
        [account save];

        [[UIApplication sharedApplication].keyWindow chooseRootViewController];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        DDLogDebug(@"换取AccessToken失败 = %@", error);
    }];

}

//开始加载时调用
- (void)webViewDidStartLoad:(UIWebView *)webView {

//    提示用户
    [SVProgressHUD showWithStatus:@"正在加载ing..."maskType:SVProgressHUDMaskTypeGradient];

}
//加载完毕时调用
- (void)webViewDidFinishLoad:(UIWebView *)webView {

//    隐藏提示
    [SVProgressHUD dismiss];

}
//加载错误是调用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {

//    隐藏提示
    [SVProgressHUD dismiss];
}

@end





